<?php

use Ifsnop\Mysqldump as IMysqldump;

//添加定时任务周期
function baidupan_add_schedules($schedules)
{
	$schedules['weekly'] = array(
		'interval' => 604800,
		'display' => '每周一次',
	);
	$schedules['monthly'] = array(
		'interval' => 2592000,
		'display' => '每月一次',
	);
	return $schedules;
}
add_filter('cron_schedules', 'baidupan_add_schedules', 10, 1);

//删除任务
function baidupan_delete_cron()
{
	if (wp_next_scheduled('baidupan')) {
		wp_clear_scheduled_hook('baidupan');
	}
}

//任务挂接函数
function baidupan_cron_fun()
{
	$error = baidupan_backup_mysql();
	if ($error->get_error_message('error')) {
		$msg = $error->get_error_message('error');
	} else {
		$msg = '备份数据库成功：<br>&nbsp;&nbsp;&nbsp;&nbsp;时间：' . wp_date('Y年n月j日 H:i:s') . '<br>&nbsp;&nbsp;&nbsp;&nbsp;文件：' . $error->get_error_message('info');
	}

	baidupan_mail($msg, '定时备份通知');
}
add_action('baidupan', 'baidupan_cron_fun');

//发送邮件
function baidupan_mail($msg, $title = '')
{
	$blogname = get_bloginfo('name');
	$adminemail = get_bloginfo('admin_email');
	if (!$title) {
		$title = '备份通知';
	}
	$title = $blogname . ' - ' . $title;
	$headers = array('Content-Type: text/html; charset=UTF-8');
	wp_mail($blogname . ' <' . $adminemail . '>', $title, $msg, $headers);
}

//备份数据库
function baidupan_backup_mysql()
{
	if (function_exists('set_time_limit')) {
		set_time_limit(0);
	}

	$error = new WP_Error;

	$suffix = wp_date('j');
	$temp_dir = sys_get_temp_dir() . '/';
	$filename = 'db_' . DB_NAME . '_' . $suffix;
	$temp = $temp_dir . $filename . '.sql';
	try {
		$dump = new IMysqldump\Mysqldump('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
		$dump->start($temp);
	} catch (\Exception $e) {
		$error->add('error', $e->getMessage());
	}

	if (!$error->has_errors()) {
		//打包文件
		$file = $temp_dir . $filename . '.zip';
		$zip = new \ZipArchive;
		if ($zip->open($file, ZIPARCHIVE::CREATE) === true) {
			$zip->addFile($temp, $filename . '.sql');
			$zip->close();

			//上传
			$baidupan = new Pcs;
			$upload = $baidupan->upload($file, '/db/' . $filename . '.zip');
			if (is_array($upload)) {
				$error->add('info', $upload['server_filename']);
			} else {
				$error->add('error', $baidupan->getError());
			}
		} else {
			$error->add('error', '打包数据库文件失败');
		}

		if (file_exists($file)) unlink($file);
	}

	if (file_exists($temp)) unlink($temp);

	return $error;
}

//获取所有附件ID
function baidupan_get_attachment_ids()
{
	global $wpdb;
	$ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type='attachment'");
	return $ids;
}

//获取缩略图
function baidupan_images($meta)
{
	if (!$meta) {
		return [];
	}

	$upload_path = get_option('upload_path');
	$upload_path = $upload_path ? trim($upload_path, '/') : 'wp-content/uploads';

	$images[] = $upload_path . '/' . $meta['file'];

	if (empty($meta['sizes'])) {
		return $images;
	}


	$path = dirname($meta['file']);
	$path = $path == '.' ? '' : '/' . $path;
	foreach ($meta['sizes'] as $size) {
		if (!$size['file']) continue;
		$images[] = $upload_path . $path . '/' . $size['file'];
	}
	$images = array_unique($images);
	return $images;
}

//初始化同步
function baidupan_initialize_sync($attachments)
{
	$error = new WP_Error;

	$files = array();
	foreach ($attachments as $attachment) {
		if (wp_attachment_is_image($attachment)) {
			$meta = wp_get_attachment_metadata($attachment);
			$images = baidupan_images($meta);
			foreach ($images as $image) {
				if (!$image) continue;
				$files[] = ABSPATH . $image;
			}
		} else {
			$files[] = get_attached_file($attachment);
		}
	}

	foreach ($files as $file) {
		$target = str_replace(ABSPATH, '/', $file);
		$baidupan = new Pcs;
		$upload = $baidupan->upload($file, $target);
		if (!is_array($upload)) {
			$error->add('error', $target . '：' . $baidupan->getError());
		}
	}

	if ($error->has_errors()) {
		$msg = '初始同步错误报告：<br><br>';
		$msg .= join('<br>', $error->get_error_messages('error'));
	} else {
		$msg = '初始同步已完成，共备份' . count($files) . '个文件';
	}

	baidupan_mail($msg, '初始同步报告');

	return $msg;
}

//上传文件时同步
function baidupan_generate_metadata($meta, $attachment)
{
	if (function_exists('set_time_limit')) {
		set_time_limit(0);
	}

	$error = new WP_Error;

	$files = array();
	if (wp_attachment_is_image($attachment)) {
		$meta = wp_get_attachment_metadata($attachment);
		$images = baidupan_images($meta);
		foreach ($images as $image) {
			if (!$image) continue;
			$files[] = ABSPATH . $image;
		}
	} else {
		$files[] = get_attached_file($attachment);
	}

	foreach ($files as $file) {
		$target = str_replace(ABSPATH, '', $file);
		$baidupan = new Pcs;
		$upload = $baidupan->upload($file, $target);
		if (!is_array($upload)) {
			$error->add('error', $target . '：' . $baidupan->getError());
		}
	}

	if ($error->has_errors()) {
		$msg = '文件备份错误报告：<br><br>';
		$msg .= join('<br>', $error->get_error_messages('error'));
		baidupan_mail($msg, '文件备份错误通知');
	}

	return $meta;
}
add_filter('wp_generate_attachment_metadata', 'baidupan_generate_metadata', 10, 2);

//同步删除
function baidupan_delete_attachment($attachment)
{
	if (function_exists('set_time_limit')) {
		set_time_limit(0);
	}

	$error = new WP_Error;

	$files = array();
	if (wp_attachment_is_image($attachment)) {
		$meta = wp_get_attachment_metadata($attachment);
		$backup_sizes = get_post_meta($attachment, '_wp_attachment_backup_sizes', true);
		if ($backup_sizes) {
			$meta['sizes'] = wp_parse_args($meta['sizes'], $backup_sizes);
		}
		$images = baidupan_images($meta);
		foreach ($images as $image) {
			if (!$image) continue;
			$files[] = $image;
		}
	} else {
		$files[] = str_replace(ABSPATH, '/', get_attached_file($attachment));
	}

	$baidupan = new Pcs;
	$delete = $baidupan->delete($files);
	if (!$delete) {
		$error->add('error', $baidupan->getError());
	}

	if ($error->has_errors()) {
		$msg = '删除文件错误报告：<br><br>';
		$msg .= join('<br>', $error->get_error_messages('error'));
		baidupan_mail($msg, '删除文件错误通知');
	}
}
add_action('delete_attachment', 'baidupan_delete_attachment', 10, 1);
